﻿using Minecraft.BLL.mysql;
using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Model;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Minecraft.ServerHall.Cmd
{
	/// <summary>
	/// 玩家登录
	/// </summary>
	public class PlayerLogin : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Player_PlayerLogin;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<PlayerLoginReq>(session);
			if (req == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：请求实体为空）" });
				return;
			}
			if (session.minecraftSessionInfo.IsLogin)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误（原因：已经登录了，不能重复调用接口）" });
				return;
			}
			if (req.PlayerId <= 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "PlayerId <= 0" });
				return;
			}
			var player = PlayerbasisBLL.GetSingleOrDefault(req.PlayerId, out bool fromCache);
			if (player == null || player.PlayerId <= 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "玩家信息不存在" });
				return;
			}

			var timeNow = DateTimeOffset.Now;

			var otherSession = session.AppServer.GetSessions(m =>
				m.minecraftSessionInfo != null && m.minecraftSessionInfo.player != null
				&& m.minecraftSessionInfo.player.PlayerId == player.PlayerId
			).ToList();
			if (otherSession != null && otherSession.Count() > 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误（原因：playerId为【{player.PlayerId}】已经被其他玩家登录）" });
				return;
			}

			//测试，只允许测试Ip用 playerId 为 1 或者 2 登录
			if (JsonConfig.Value.IsTest)
			{
				var idLi = new List<int> { 1, 2 };
				if (idLi.Any(m => m == player.PlayerId))
				{
					if (!JsonConfig.Value.TestIps.ToList().Any(m => m == session.RemoteEndPoint.Address.ToString()))
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"该playerId为测试id，请更换playerId（playerId大于等于【{idLi.Max() + 1}】的可以使用）" });
						return;
					}
				}
			}

			//首次登录
			if (!player.IsLoggedIn_Convert)
			{
				player.IsLoggedIn = 1;
				//初次登录，重置随机宝箱（mapId一定是基地id）
				session.ResetTreasurebox(false, MinecraftConfig.BaseMapId);
			}

			//登录成功，初始化数据
			player.LastLoginTime = timeNow;
			session.minecraftSessionInfo.IsLogin = true;
			session.minecraftSessionInfo.IsLoginAfterThreadRunning = true;
			session.minecraftSessionInfo.player = player;
			//物品信息（快捷栏、背包物品、装备、产出家具）
			session.minecraftSessionInfo.goodsList = GoodsBLL.GetListAll(session.minecraftSessionInfo.player.PlayerId, out fromCache);
			//快捷栏格子个数初始化
			session.minecraftSessionInfo.ShortcutBarCellNum = MinecraftConfig.ShortcutBarCellInitNum;
			//家具信息初始化
			session.InitFurnitureListFromDb();
			//地图信息
			session.minecraftSessionInfo.map = MapBLL.GetSingleOrDefault(session.minecraftSessionInfo.player.PlayerId, out fromCache);
			session.IntoBase(session.minecraftSessionInfo.map.SourceMapId);

			//掉落信息列表
			session.minecraftSessionInfo.dropinfoList = DropinfoBLL.GetList(session.minecraftSessionInfo.player.PlayerId, out fromCache);
			//蓝图信息
			session.minecraftSessionInfo.blueprint = BlueprintBLL.GetSingleOrDefault(session.minecraftSessionInfo.player.PlayerId, out fromCache);
			//幸存者列表信息
			session.minecraftSessionInfo.survivorList = SurvivorBLL.GetList(session.minecraftSessionInfo.player.PlayerId, out fromCache);
			//尸潮信息
			session.minecraftSessionInfo.zombiesbrushInfo = ZombiesbrushBLL.GetSingleOrDefault(session.minecraftSessionInfo.player.PlayerId, out fromCache);

			//体力值（数据重新设置）
			session.SetCurPhysicalStrengthValue();

			//装备部分（数据重新赋值）
			session.minecraftSessionInfo.player.Fight_Defense = MinecraftConfig.PlayerInitDefense;
			session.minecraftSessionInfo.BackpackCellNum = MinecraftConfig.BackpackCellInitNum;

			var equipmentList = session.minecraftSessionInfo.goodsList.Where(m => m.enumGoodsBelongsToType_Convert == EnumGoodsBelongsToType.Equipment).ToList();
			if (equipmentList != null && equipmentList.Any())
			{
				foreach (var equipment in equipmentList)
				{
					//Mod_Items mod_Items = CsvConfig.itemsList.FirstOrDefault(m => m.Id == equipment.GoodsItemId);
					Mod_Items mod_Items = CsvConfig.GetMod_ItemsInfoById(equipment.GoodsItemId);
					if (mod_Items != null)
					{
						switch (mod_Items.modAttributeInfo_Convert.enumAttribute)
						{
							case EnumAttribute.Def:
								{
									session.minecraftSessionInfo.player.Fight_Defense += mod_Items.modAttributeInfo_Convert.Value;
								}
								break;
							case EnumAttribute.BagSize:
								{
									session.minecraftSessionInfo.BackpackCellNum += mod_Items.modAttributeInfo_Convert.Value;
								}
								break;
							case EnumAttribute.Atk:
								{

									session.minecraftSessionInfo.player.Fight_Attack += mod_Items.modAttributeInfo_Convert.Value;
								}
								break;
							default:
								{
									session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：登录接口中，暂不支持该属性【{mod_Items.modAttributeInfo_Convert.Id}:{mod_Items.modAttributeInfo_Convert.enumAttribute.ToString()}】加点）" });
									return;
								}
						}
					}
				}
			}
			var goodsInfo = session.minecraftSessionInfo.goodsList.FirstOrDefault(m =>
				m.enumGoodsBelongsToType_Convert == EnumGoodsBelongsToType.ShortcutBar
				&& m.GoodsPosition == session.minecraftSessionInfo.player.ShortcutBarWeaponPos
				&& m.guid == "");
			if (goodsInfo != null)
			{
				Mod_Items mod_ItemsWeapon = CsvConfig.GetMod_ItemsInfoById(goodsInfo.GoodsItemId);
				if (mod_ItemsWeapon != null)
				{
					if (mod_ItemsWeapon.enumGoodsType_Convert == EnumGoodsType.Weapon)
					{
						session.minecraftSessionInfo.player.Fight_Attack += mod_ItemsWeapon.modAttributeInfo_Convert.Value;
					}
				}
			}

			//属性值列表
			List<KeyValueEnumAttributeInt> equipmentAttributeList = new List<KeyValueEnumAttributeInt>();
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.Def, value = session.minecraftSessionInfo.player.Fight_Defense });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.BagSize, value = session.minecraftSessionInfo.BackpackCellNum });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.Atk, value = session.minecraftSessionInfo.player.Fight_Attack });

			//线程启动
			//ServerThreadPoolTest.Start(session);

			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.Level, value = session.minecraftSessionInfo.player.Level_Convert });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurExp, value = session.minecraftSessionInfo.player.Exp });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurHp, value = session.minecraftSessionInfo.player.Human_Life });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.HpMax, value = MinecraftConfig.PlayerInitHp });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurFeed, value = session.minecraftSessionInfo.player.Human_Hunger });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurClear, value = session.minecraftSessionInfo.player.Human_Clean });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurToilet, value = session.minecraftSessionInfo.player.Human_GoToilet });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.MoveSpeed, value = session.minecraftSessionInfo.player.Fight_TravelRate });
			equipmentAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.AtkSpeed, value = session.minecraftSessionInfo.player.Fight_AttackSpeed });

			//从数据库查出来此用户的成就信息
			session.minecraftSessionInfo.playerAchievement = AchievementBLL.GetSingleOrDefault(session.minecraftSessionInfo.player.PlayerId, out fromCache);

			var resp = new PlayerLoginResp
			{
				//预留（刘威）
				//BackpackCellNum = session.minecraftSessionInfo.BackpackCellNum,
				//Exp = session.minecraftSessionInfo.player.Exp,
				//Fight_Attack = session.minecraftSessionInfo.player.Fight_Attack,
				//Fight_AttackSpeed = session.minecraftSessionInfo.player.Fight_AttackSpeed,
				//Fight_Defense = session.minecraftSessionInfo.player.Fight_Defense,
				//Fight_TravelRate = session.minecraftSessionInfo.player.Fight_TravelRate,
				//Human_Clean = session.minecraftSessionInfo.player.Human_Clean,
				//Human_GoToilet = session.minecraftSessionInfo.player.Human_GoToilet,
				//Human_Hunger = session.minecraftSessionInfo.player.Human_Hunger,
				//Human_Life = session.minecraftSessionInfo.player.Human_Life,

				PhysicalStrengthValue = session.minecraftSessionInfo.player.PhysicalStrengthValue, //配置表中暂时没有该属性
				PhysicalStrengthValueDistanceSeconds = Convert.ToInt32((timeNow - session.minecraftSessionInfo.player.PhysicalStrengthLastGrowTime).TotalSeconds),

				Name = session.minecraftSessionInfo.player.Name,
				PlayerId = session.minecraftSessionInfo.player.PlayerId,
				equipmentAttributeList = equipmentAttributeList,
				GoldCoin = session.minecraftSessionInfo.player.GoldCoin,
				Achivement = session.minecraftSessionInfo.playerAchievement
			};



			session.Send(defCommand, req, resp);

			if (JsonConfig.Value.IsDebug)
			{
				SessionLoginAfterTest.Do(session);
			}
		}
	}
}
